<template>
  <view class="comp-uploader">
    <block v-for="(item, index) in imageList" :key="index">
      <view class="comp-uploader__item">
        <image
          class="comp-uploader__item-img"
          :src="item.filePath"
          mode="aspectFit"
          @click="previewImage(index)"
        />
        <text class="iconfont icon-close" @click="delImage(index)" />
        <view class="comp-uploader__progress" v-if="item.progress < 100"
          >{{ item.progress }}%</view
        >
      </view>
    </block>
    <view
      class="comp-uploader__add"
      v-if="rduLength > 0"
      @click="chooseImage"
    ></view>
  </view>
</template>

<script>
import { BASE_URL } from '@/config';

export default {
  data() {
    return {
      imageList: [],
    };
  },

  props: {
    value: {},

    count: {
      type: Number,
      value: 4, //单次可选择的图片数量
    },

    maxLength: {
      type: Number,
      value: 50, //可上传总数量
    },
  },

  computed: {
    rduLength() {
      return this.maxLength - this.imageList.length;
    },
  },

  methods: {
    //选择图片
    chooseImage: function () {
      uni.chooseImage({
        count: this.rduLength < this.count ? this.rduLength : this.count, //最多可以选择的图片张数，默认9
        sizeType: ['original', 'compressed'], //original 原图，compressed 压缩图，默认二者都有
        sourceType: ['album'], //album 从相册选图，camera 使用相机，默认二者都有
        success: (res) => {
          const images = res.tempFilePaths;
          this.uploadFiles(images);
        },
      });
    },

    //上传图片
    async uploadFiles(images) {
      this.imageList.push({
        filePath: images[0],
        progress: 0,
      });
      this.$store.commit('showLoading', { text: '上传中' });

      let uploadUrl = '';
      try {
        uploadUrl = await this.uploadImage(images[0]);
      } catch (err) {
        console.log(err);
        return;
      }

      if (uploadUrl !== false) {
        images.splice(0, 1);
        this.imageList[this.imageList.length - 1].src = uploadUrl;

        //判断是否需要继续上传
        if (images.length > 0 && this.rduLength > 0) {
          this.uploadFiles(images);
        } else {
          this.$store.commit('hideLoading');
        }
      } else {
        //上传失败处理
        this.imageList.pop();
        this.$store.commit('hideLoading');
        uni.showToast({
          title: '上传中出现问题，已终止上传',
          icon: 'none',
          mask: true,
          duration: 2000,
        });
      }
      this.$emit('update:value', this.imageList);
    },

    uploadImage: function (file) {
      return new Promise((resolve, reject) => {
        //发送给后端的附加参数
        const formData = {
          thumb_mode: 1,
        };
        this.uploadTask = uni.uploadFile({
          url: `${BASE_URL}/api/front/upload-img`,
          filePath: file,
          name: 'file',
          formData: formData,
          success(res) {
            const result = JSON.parse(res.data) || {};
            if (result.ok && result.data) {
              resolve(result.data.url);
            } else {
              reject('接口返回错误');
            }
          },
          fail() {
            reject('网络链接错误');
          },
        });
        //上传进度
        this.uploadTask.onProgressUpdate((progressRes) => {
          this.imageList[this.imageList.length - 1].progress =
            progressRes.progress;
          this.$emit('update:value', this.imageList);
        });
      });
    },

    //删除图片
    delImage: function (index) {
      uni.showModal({
        title: '提示',
        content: '确定要放弃这张图片么？',
        success: (confirmRes) => {
          if (confirmRes.confirm) {
            this.imageList.splice(index, 1);
            this.$emit('update:value', this.imageList);
          }
        },
      });
    },

    //预览图片
    previewImage: function (index) {
      const urls = [];
      this.imageList.forEach((item) => {
        urls.push(item.filePath);
      });
      uni.previewImage({
        current: urls[index],
        urls: urls,
        indicator: 'number',
      });
    },
  },
};
</script>

<style lang="scss">
.comp-uploader {
  padding: 24rpx 0;
  background-color: #fff;
  overflow: hidden;

  &__item {
    position: relative;
    float: left;
    width: 150rpx;
    height: 150rpx;
    margin-right: 30rpx;
    &:nth-child(4n) {
      margin-right: 0;
    }

    &-img {
      width: 100%;
      height: 100%;
      border-radius: 8rpx;
    }

    .icon-close {
      position: absolute;
      right: -16rpx;
      top: -14rpx;
      width: 36rpx;
      height: 36rpx;
      line-height: 36rpx;
      border-radius: 100px;
      font-size: 28rpx;
      background: #ccc;
      color: #fff;
      text-align: center;
    }
  }

  &__progress {
    position: absolute;
    left: 0;
    top: 0;
    display: flex;
    align-items: center;
    justify-content: center;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.4);
    color: #fff;
    font-size: 24rpx;
    border-radius: 8rpx;
  }

  &__add {
    position: relative;
    float: left;
    width: 150rpx;
    height: 150rpx;
    z-index: 99;
    border-radius: 8rpx;
    background: #f9f9f9;
    &:before,
    &:after {
      content: ' ';
      position: absolute;
      top: 50%;
      left: 50%;
      -webkit-transform: translate(-50%, -50%);
      transform: translate(-50%, -50%);
      width: 4rpx;
      height: 60rpx;
      background-color: #d6d6d6;
    }
    &:after {
      width: 60rpx;
      height: 4rpx;
    }
    &:active {
      background-color: #f7f7f7;
    }
  }
}
</style>
